﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DGSFramework;
using System.Web.Security;
using ActiveUp.Net.Mail;
using OpenPop.Pop3;

namespace Framework.WebmasterTool
{
    public partial class HostMail : System.Web.UI.Page
    {
        DGSFrameworkEntities entity = new DGSFrameworkEntities();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                CheckPermission();
                loadConfigMailServer();
            }
        }

        public void CheckPermission()
        {
            MembershipUser someUser = Membership.GetUser();
            if (someUser == null)
            {
                Response.Redirect(Globals.ApplicationPath + "LoginAdmin/Default.aspx");
            }
            bool flag = false;
            var user = entity.aspnet_Users.Where(us => us.UserName == someUser.UserName).FirstOrDefault();
            user.aspnet_Roles.Load();
            var rolesForUser = user.aspnet_Roles.ToList();
            foreach (var item in rolesForUser)
            {
                var permission = entity.udv_Permissions.Where(ps => ps.RoleId == item.RoleId).FirstOrDefault();
                if (permission.Mailserver.Value == true)
                {
                    flag = true;
                }
            }
            if (flag == false)
            {
                lblPermissionMessage.Visible = true;
                Panel1.Visible = false;
            }
        }

        protected void loadConfigMailServer()
        {
            udv_EmailHostSetting emailHostSetting = entity.udv_EmailHostSetting.OrderByDescending(es => es.EmailHostSettingID).FirstOrDefault();
            txtSmtp.Text = emailHostSetting.ServerMailSMTP.Trim();
            txtSmtpPort.Text = emailHostSetting.PortMailSMTP.Value.ToString();
            txtImap.Text = emailHostSetting.ServerMailIMAP.Trim();
            txtImapPort.Text = emailHostSetting.PortMailIMAP.Value.ToString();
            txtUsername.Text = emailHostSetting.MailAccount.Trim();
            txtPassword.Text = Globals.Base64Decode(emailHostSetting.Password.Trim());
            if (emailHostSetting.Password == null || emailHostSetting.Password.Trim() == "")
            {
                lblMessagePass.Text = "Chưa cấu hình Password";
            }
            else
            {
                lblMessagePass.Text = "Đã cấu hình Password";
            }
            txtEmailTo.Text = emailHostSetting.MailReceive.Trim();
            chkSSL.Checked = emailHostSetting.SSL.Value;
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                udv_EmailHostSetting emailHostSetting = entity.udv_EmailHostSetting.OrderByDescending(es => es.EmailHostSettingID).FirstOrDefault();
                emailHostSetting.ServerMailSMTP = txtSmtp.Text.Trim();
                emailHostSetting.PortMailSMTP = int.Parse(txtSmtpPort.Text);
                emailHostSetting.ServerMailIMAP = txtImap.Text.Trim();
                emailHostSetting.PortMailIMAP = int.Parse(txtImapPort.Text);
                emailHostSetting.MailAccount = txtUsername.Text.Trim();
                if (txtPassword.Text != "")
                {
                    emailHostSetting.Password = Globals.Base64Encode(txtPassword.Text);
                }
                emailHostSetting.MailReceive = txtEmailTo.Text.Trim();
                emailHostSetting.SSL = chkSSL.Checked;
                entity.SaveChanges();
                lblMessage.ForeColor = System.Drawing.Color.Blue;
                lblMessage.Text = "Cấu hình gửi mail thành công.";
                loadConfigMailServer();

                //create db log
                CreateDBLog(null, null, TypeAction.Update, "Cập nhật cấu hình gửi mail", "", "", "", "", "", "", "", "");
            }
            catch
            {
                lblMessage.ForeColor = System.Drawing.Color.Red;
                lblMessage.Text = "Cấu hình gửi mail không thành công. Hãy thử lại.";
            }
        }

        protected void btnTestMail_Click(object sender, EventArgs e)
        {
            bool flagImap = false;
            udv_EmailHostSetting emailHostSetting = entity.udv_EmailHostSetting.OrderByDescending(es => es.EmailHostSettingID).FirstOrDefault();
            Imap4Client imap = new Imap4Client();
            Pop3Client pop3 = new Pop3Client();
            try
            {
                if (emailHostSetting.SSL == false)
                    imap.Connect(emailHostSetting.ServerMailIMAP, emailHostSetting.PortMailIMAP.Value);
                else
                    imap.ConnectSsl(emailHostSetting.ServerMailIMAP, emailHostSetting.PortMailIMAP.Value);
                flagImap = true;
            }
            catch
            {
                try
                {
                    pop3.Connect(emailHostSetting.ServerMailIMAP, emailHostSetting.PortMailIMAP.Value, emailHostSetting.SSL.Value);
                    flagImap = false;
                }
                catch
                {
                    string message = "Lỗi kết nối email. Sai cấu hình mail server";
                    ScriptManager.RegisterStartupScript(this.UpdatePanel1, typeof(string), "alertScript", "jAlert('" + message + "', '" + "Thông báo" + "');", true);
                    return;
                }
            }
            if (flagImap == true)
            {
                try
                {
                    imap.Login(emailHostSetting.MailAccount, Globals.Base64Decode(emailHostSetting.Password));
                    string message = "Kết nối email imap thành công";
                    ScriptManager.RegisterStartupScript(this.UpdatePanel1, typeof(string), "alertScript", "jAlert('" + message + "', '" + "Thông báo" + "');", true);
                }
                catch
                {
                    string message = "Lỗi kết nối email imap. Sai username hoặc password";
                    ScriptManager.RegisterStartupScript(this.UpdatePanel1, typeof(string), "alertScript", "jAlert('" + message + "', '" + "Thông báo" + "');", true);
                }
            }
            else
            {
                try
                {
                    pop3.Authenticate(emailHostSetting.MailAccount, Globals.Base64Decode(emailHostSetting.Password));
                    string message = "Kết nối email pop3 thành công";
                    ScriptManager.RegisterStartupScript(this.UpdatePanel1, typeof(string), "alertScript", "jAlert('" + message + "', '" + "Thông báo" + "');", true);
                }
                catch
                {
                    string message = "Lỗi kết nối email pop3. Sai username hoặc password";
                    ScriptManager.RegisterStartupScript(this.UpdatePanel1, typeof(string), "alertScript", "jAlert('" + message + "', '" + "Thông báo" + "');", true);
                }
            }
        }

        public void CreateDBLog(int? postID, int? postCateID, TypeAction typeAction, string title, string _abstract, string description,
        string releaseDate, string expireDate, string isApproved, string statusID, string metaDescription, string metaKeywords)
        {
            udv_Log log = new udv_Log();
            log.PostID = postID;
            log.PostCateID = postCateID;
            log.TypeAction = (int)typeAction;
            log.Title = title;
            log.Abstract = _abstract;
            log.Description = description;
            log.ReleaseDate = releaseDate;
            log.ExpireDate = expireDate;
            log.IsApproved = isApproved;
            log.StatusID = statusID;
            log.MetaDescription = metaDescription;
            log.MetaKeywords = metaKeywords;
            log.ActionedDate = DateTime.Now;
            log.ActionBy = Membership.GetUser().UserName;
            log.IpAdress = Globals.GetClientIPAddress();

            entity.AddToudv_Log(log);
            entity.SaveChanges();
        }
    }
}